package com.gzy.rpsm_property.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gzy.rpsm_property.mapper.AmountMapper;
import com.gzy.rpsm_property.mapper.PayMapper;
import com.gzy.rpsm_property.mapper.UserMapper;
import com.gzy.rpsm_property.pojo.Amount;
import com.gzy.rpsm_property.pojo.PageResult;
import com.gzy.rpsm_property.pojo.PayInfo;
import com.gzy.rpsm_property.pojo.User;
import com.gzy.rpsm_property.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

@Service
public class PayServiceImpl implements PayService {
    @Autowired
    PayMapper payMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmountMapper amountMapper;

    @Override
    public PageResult<PayInfo> pageOfPayInfo(Integer current,
                                             Integer size, LocalDate start, LocalDate end, String username,
                                             String idCard, Integer floorId, Integer buildingId) {
        PageHelper.startPage(current,size);
        Page<PayInfo> page = payMapper.selectPayInfoOnCondition(start,end,username,idCard,floorId,buildingId);
        return PageResult.restPage(page);
    }
    @Override
    public boolean payForUser(String username, Integer userRoomId, Integer paymentAmount) {
        User user = userMapper.getUserByRoomIdAndUsername(userRoomId, username);
        if (user == null) {
            throw new IllegalArgumentException("用户不存在");
        }

        List<Amount> unpaidAmounts = amountMapper.getUnpaidAmountsByRoomIdAndUsername(userRoomId, username);
        int totalUnpaidAmount = unpaidAmounts.stream().mapToInt(Amount::getAmount).sum();

        if (paymentAmount < totalUnpaidAmount) {
            throw new IllegalArgumentException("支付金额不足");
        }

        for (Amount amount : unpaidAmounts) {
            if (paymentAmount >= amount.getAmount()) {
                amountMapper.updateAmountPayment(amount.getAmount_id(), amount.getAmount()); // 传递当前 Amount 对象的实际金额
                paymentAmount -= amount.getAmount();
            } else {
                // 如果支付金额不足以支付当前欠款，则抛出异常或部分支付逻辑
                throw new IllegalArgumentException("支付金额不足以支付当前欠款");
            }
        }

        return true;
    }
}